/*
 * AbstractRestController.java
 * Copyright (c) 2014, 2019, Kiri. 
 * All rights reserved.
 */
package com.onesalt.web.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import com.onesalt.common.ExceptionConstants;
import com.onesalt.domain.User;
import com.onesalt.domain.UserLogin;
import com.onesalt.service.LogService;
import com.onesalt.service.LoginService;
import com.onesalt.service.UserService;
import com.onesalt.utils.EncryptUtil;
import com.onesalt.web.AbstractController;
import com.onesalt.web.api.request.Request;

/**
 * 
 *
 * @author kiri
 * @date 2015年4月19日
 * @version 1.0
 */
@RestController
public class AbstractRestController extends AbstractController {

	@Autowired
	private UserService userService;

	@Autowired
	private LoginService loginService;
	
	@Autowired
	private LogService logService;
	
	protected UserService getUserService() {
		return userService;
	}

	protected LoginService getLoginService() {
		return loginService;
	}

	protected LogService getLogService() {
		return logService;
	}
	
	public User getValidUser(Request request) {
		return getValidUser(request.getToken(), request.getDeviceId());
	}
	
	public User getValidUser(String token, String deviceId) {
		long userId = EncryptUtil.getUserId(token);
		do {
			if (userId == 0) {
				break;
			}
			
			User user = getUserService().getUserRepository().findOne(userId);
			getLogger().debug("login, user = " + user + ", userId = " + userId);
			if (user == null) {
				throw ExceptionConstants.USER_NOT_EXISTS_EXCEPTION;
			}
			
			UserLogin login = getLoginService().getUserLoginRepository().findByToken(token);
			getLogger().debug("login = " + login + ", token = " + token);
			if (login == null) {
				break;
			}
			
//			if (StringUtils.hasText(deviceId) && deviceId.equals(login.getDeviceId())) {
				user.setLogin(login);
				return user;
//			}
		} while (false);
		
		throw ExceptionConstants.NEED_RELOGIN_EXCEPTION;
	}
}
